package com.powerunion.datacollection.dao.impl;

import java.io.BufferedReader;
import java.io.Reader;
import java.io.Writer;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;


import oracle.jdbc.OracleResultSet;
import oracle.sql.CLOB;

import org.apache.log4j.Logger;

import com.powerunion.datacollection.common.Constants;
import com.powerunion.datacollection.dao.DaoException;
import com.powerunion.datacollection.dao.FormDao;
import com.powerunion.datacollection.model.Form;
import com.powerunion.util.DBUtils;
import com.powerunion.util.log.LogHelper;
import com.powerunion.util.query.jdbc.QueryParameters;


public class FormDaoImpl extends JdbcBase implements FormDao {
	// 初始化日志类
	private static final Logger logger = LogHelper.getInstance().getLogger(
			FormDaoImpl.class);

	protected static final String sqlGetBYKey=  "select fset_id,maintbl_form_CONT,target_form_cont from dc_form where fset_id=?";
	//protected static final String sqlInsertMainTblFormCONT = "insert into dc_form(fset_id,maintbl_form_cont) values(?,?)";
	protected static final String sqlInsertMainTblFormCONT = "select maintbl_form_cont from dc_form where fset_id=? for update";
	protected static final String sqlUpdateMainTblFormCONT = "update dc_form set maintbl_form_cont=? where fset_id=?";
	
	public boolean saveMainTblFormCONT(Form form) throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug(Constants.INTOMETHOD + "save");
		}

		boolean isSuccess = false;

		String sql = "";
		String sql2 = "";
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		Writer writer = null;
		try {
			conn = this.getConnection();
			conn.setAutoCommit(false);
			Form iform = this.findFormByKey(form.getFsetId());
			sql = sqlInsertMainTblFormCONT;
			if (iform == null) {//新增
				sql2 = "insert into dc_form(maintbl_form_cont,fset_id) values(empty_clob(),?)";
			} else {//修改
				//清空原clob对象
				sql2 = "update dc_form set maintbl_form_cont=empty_clob() where fset_id=?";

			}
			
			ps = conn.prepareStatement(sql2);
			ps.setString(1, form.getFsetId());
			ps.executeUpdate();
			
			ps = conn.prepareStatement(sql);
			ps.setString(1, form.getFsetId());
			rs = ps.executeQuery();
			if(rs.next()) {
				oracle.sql.CLOB clob = (oracle.sql.CLOB)rs.getClob(1);
				writer = clob.getCharacterOutputStream();
				writer.write(form.getMainTblFormCONT());
				writer.flush();
			}
			conn.commit();
			if (logger.isDebugEnabled()) {
				logger.debug("save:" + Constants.SAVE + "主表报送区"
						+ Constants.SUCCESS);
			}
			isSuccess = true;
		
			
		} catch (Exception e) {
			
			if(conn != null){
				try{
					conn.rollback();
				}catch(SQLException e1){
					e1.printStackTrace();
				}
			}
			logger.error("save:" + Constants.SAVE + "主表报送区" + Constants.FAIL,e);
			return false;
		}finally{
			if(writer != null){
				writer.close();
				writer = null;
			}
			DBUtils.close(rs,ps, conn);
		}
	
		return isSuccess;
	}

	public Form findFormByKey(String id) throws DaoException {
		String sql =  sqlGetBYKey;
		QueryParameters params = new QueryParameters();
		params.addParameter(id, Types.VARCHAR);
		Form form = null;
		try {
			form = (Form) this.findByKey(sql, params, "getForm");
		} catch (Exception e) {
			logger.error("findFormByKey:" + Constants.SEARCH + "form"
					+ Constants.FAIL,e);
			throw new DaoException("search db record error!");
		}

		return form;
	}

	public final Form getForm(ResultSet rs) throws Exception {
		Form form = new Form();

		form.setFsetId(rs.getString("fset_id"));
		
//		java.sql.Clob maintblClob  = rs.getClob("maintbl_form_CONT");
//		java.sql.Clob targetFormCont  = rs.getClob("target_form_cont");
		CLOB maintblClob  = ((OracleResultSet)rs).getCLOB("maintbl_form_CONT");
		CLOB targetFormCont  = ((OracleResultSet)rs).getCLOB("target_form_cont");
		
		form.setMainTblFormCONT(this.ClobToString(maintblClob));
		form.setTargetFormCont(this.ClobToString(targetFormCont));

		return form;
	}
	
	// 将字CLOB转成STRING类型 
	private String ClobToString(CLOB clob) throws Exception {

		if(clob == null)return "";
		String reString = "";
		Reader is = clob.getCharacterStream();// 得到流
		BufferedReader br = new BufferedReader(is);
		StringBuffer sb = new StringBuffer();
		try{
			String s = br.readLine();
			
			while (s != null) {// 执行循环将字符串全部取出付值给StringBuffer由StringBuffer转成STRING
				sb.append(s);
				s = br.readLine();
			}
			
		}catch (Exception e) {
			logger.error("读取内容出错: " + e);
			throw new Exception("读取内容出错! " + e);
		} finally {
			if (is != null){
				is.close();
				is = null;
			}
			if (br != null){
				br.close();
				br = null;
			}
		}

		reString = sb.toString();
		return reString;
	} 
	
	


}
